# coding:utf-8
# 测试服务器部署脚本
# 需要本地python环境 远程服务器执行脚本
# 本文件用于本地打包上传
import paramiko
import os
import traceback
import datetime

# alpha svn地址
alphaSvnUrl = 'https://db.winjoinit.com:8443/svn/Dev/project/泛糖科技网络货运平台/1.web/sit'
# 项目svnUrl
svnUrl = 'https://db.winjoinit.com:8443/svn/Dev/project/泛糖科技网络货运平台/1.web/prod'
# 本地项目地址 请根据情况自行修改
localPath = 'F:/Repositories/FTKJWLHYPT/front/prod'
# dist 打包后的文件夹名称 默认为dist
localDistPath = 'dist'
# 当前的打包命令
packageCommand = 'yarn prod'
# 服务器地址
serverAddr = '10.116.25.37'
# 用户名
username = 'dapp'
# 密码
password = 'YJ9t1p^DmO'
# 服务器部署路径
serverDeployPath = '/home/dapp/ftkjwlhypt/front'
# 服务器shell脚本
serverShellPath = "/home/dapp/deploy_front.sh"

frontPath = localPath + '/' + localDistPath


def pullCode():
    if not os.path.exists(localPath):
        os.makedirs(localPath)
    os.chdir(localPath)
    if len(os.listdir(localPath)) == 0:
        os.system('svn checkout ' + svnUrl + ' ' + localPath)
    else:
        os.system('svn update ' + localPath)
    # 合并分支
    os.system('svn merge ' + alphaSvnUrl + ' ' + localPath)
    os.system('svn commit -m auto')


def remove_local_old_file():
    if os.path.exists(frontPath):
        os.remove(frontPath)


def package():
    os.chdir(localPath)
    os.system('yarn install')
    code = 1
    if packageCommand != '':
        code = os.system(packageCommand)
    else:
        code = os.system('yarn sit')
    if code != 0:
        print('package error')
        exit()


def resultHanlder(stdout, stderr):
    res, err = stdout.read(), stderr.read()
    result = res if res else err
    result.decode('utf-8')
    res = result.decode(encoding='utf-8')
    return res


def progress(curr, total):
    print('\r' + 'upload >>> ' + str(round(curr / total * 100, 2)) + '%',
          end='\r',
          flush=True)


def fileUpload():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=serverAddr,
                    port=22,
                    username=username,
                    password=password)
        ssh.exec_command('rm -rf ' + serverDeployPath + '/*')
        local_dir = frontPath
        remote_dir = serverDeployPath
        t = paramiko.Transport((serverAddr, 22))
        t.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        print('upload file start %s ' % datetime.datetime.now())
        for root, dirs, files in os.walk(local_dir):
            for filespath in files:
                local_file = os.path.join(root, filespath)
                a = local_file.replace(local_dir, '')
                a = a.replace('\\', '/')
                remote_file = remote_dir + a
                try:
                    print("upload %s to remote %s" % (local_file, remote_file))
                    sftp.put(localpath=local_file,
                             remotepath=remote_file,
                             callback=progress)
                except Exception as ex:
                    sftp.mkdir(os.path.split(remote_file)[0])
                    sftp.put(local_file, remote_file)
            for name in dirs:
                local_path = os.path.join(root, name)
                a = local_path.replace(local_dir, '')
                a = a.replace('\\', '/')
                remote_path = remote_dir + a
                try:
                    sftp.mkdir(remote_path)
                    print("mkdir path %s" % remote_path)
                except Exception as e:
                    print(e)
        print('upload file success %s ' % datetime.datetime.now())
        t.close()
    except Exception as e:
        print(e)


def execDeploy():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=serverAddr,
                    port=22,
                    username=username,
                    password=password)
        stdin, stdout, stderr = ssh.exec_command('sudo sh ' + serverShellPath)
        print(resultHanlder(stdout, stderr))
    except BaseException as e:
        print(e.args)
        print(traceback.format_exc())
        exit(1)
    finally:
        ssh.close()


pullCode()
# remove_local_old_file()
package()
fileUpload()
execDeploy()
